package com.jjh.search;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.util.Version;

import com.jjh.index.IndexManager;

public class SearchManager {

	private String searchWord = "";
	private IndexManager indexManager;
	private Analyzer analyzer;
	
	public SearchManager(String searchWord) {
		this.searchWord = searchWord;
		this.indexManager = new IndexManager();
		this.analyzer = new StandardAnalyzer(Version.LUCENE_21);
	}

	/**
	 * 查询结果
	 * @return
	 */
	public List search() {
		List searchResult = new ArrayList();
		
		//没有已经生成了索引就生成索引
		if(indexManager.ifIndexExist() == false){
			//生成索引，生成失败就直接返回空结果
			try {
				if(indexManager.createIndex() == false){
					return searchResult;
				}
			} catch (IOException e) {
				e.printStackTrace();
				return searchResult;
			}
		}
		IndexSearcher indexSearcher = null;
		try{
			//生成搜索对象
			indexSearcher = new IndexSearcher(indexManager.getIndexDir());
		} catch (Exception e){
			e.printStackTrace();
		}
		
		//定义Query对象
		QueryParser queryParser = new QueryParser(Version.LUCENE_21, "content", analyzer);
		
		Query query = null;

		try{
			//创建搜索对象
			query = queryParser.parse(searchWord);
		} catch (Exception e){
			e.printStackTrace();
		}
		
		//执行搜索，并对结果进行处理
		if(query != null && indexSearcher != null){
			try{
				TopDocs topDocs = indexSearcher.search(query, 10);
				SearchResult searchResultBean = null;
				ScoreDoc[] scoreDoc = topDocs.scoreDocs;
				Document doc = null;
				
				for(int i = 0; i < topDocs.totalHits; i ++){
					searchResultBean = new SearchResult();
					doc = indexSearcher.doc(scoreDoc[i].doc);
					searchResultBean.setHtmlPath(doc.get("path"));
					searchResultBean.setHtmlTitle(doc.get("title"));
					searchResult.add(searchResultBean);
				}
			} catch (Exception e){
				
			}
		}
		
		return searchResult;
	}

}
